package com.wuliupai.delivery.wuliupaidelivery.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.mm.cme.safekeyboardlib.KeyboardTouchListener;
import com.mm.cme.safekeyboardlib.KeyboardUtil;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.wuliupai.delivery.wuliupaidelivery.App;
import com.wuliupai.delivery.wuliupaidelivery.R;
import com.wuliupai.delivery.wuliupaidelivery.bean.BaseBean;
import com.wuliupai.delivery.wuliupaidelivery.bean.MoneyBean;
import com.wuliupai.delivery.wuliupaidelivery.bean.PayBean;
import com.wuliupai.delivery.wuliupaidelivery.bean.WalletEntity;
import com.wuliupai.delivery.wuliupaidelivery.constants.BroadcastChannels;
import com.wuliupai.delivery.wuliupaidelivery.constants.Flag;
import com.wuliupai.delivery.wuliupaidelivery.constants.InterfaceNet;
import com.wuliupai.delivery.wuliupaidelivery.constants.Value;
import com.wuliupai.delivery.wuliupaidelivery.net.NetResultOperate;
import com.wuliupai.delivery.wuliupaidelivery.ui.NoScrollViewPager;
import com.wuliupai.delivery.wuliupaidelivery.utils.JsonUtils;
import com.wuliupai.delivery.wuliupaidelivery.utils.LogUtils;
import com.wuliupai.delivery.wuliupaidelivery.utils.MD5;
import com.wuliupai.delivery.wuliupaidelivery.utils.RxBus;
import com.wuliupai.delivery.wuliupaidelivery.utils.SharePreferenceUtil;
import com.wuliupai.delivery.wuliupaidelivery.utils.StringUtils;
import com.wuliupai.delivery.wuliupaidelivery.utils.TimeCountDownUtil;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import cn.bingoogolapple.qrcode.core.BGAQRCodeUtil;
import cn.bingoogolapple.qrcode.zxing.QRCodeEncoder;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by CME on 16/8/2.
 * Description 支付页面
 */
@EActivity(R.layout.act_pay_fee)
public class PayFeeActivity extends AppBaseActivity {

    @Bean(SharePreferenceUtil.class)
    SharePreferenceUtil sharePreferenceUtil;

    @ViewById(R.id.rootView)
    LinearLayout rootView;

    @ViewById(R.id.viewPager)
    NoScrollViewPager viewPager;

    @ViewById(R.id.iv_backBtn)
    ImageView iv_backBtn;//左侧的返回键
    @ViewById(R.id.iv_finishBtn)
    ImageView iv_finishBtn;//左侧关闭页面的按钮
    @ViewById(R.id.iv_rightBackBtn)
    ImageView iv_rightBackBtn;//右侧的返回键
    @ViewById(R.id.tv_title)
    TextView tv_title;//标题

    /**
     * 1 余额支付
     * 2 微信支付
     * 3 微信扫码支付
     */
    private int payType = 1;

    @Extra("payBean")
    PayBean payBean;

    private String payInfoType;//支付类型
    private long chargeLine1;//第1栏支付金额（单位：分）
    private long chargeLine2;//第2栏支付金额（单位：分）

    @Extra("onlyWeChat")
    boolean onlyWeChat = false;//是否只用微信支付
    @Extra("onlyYuePay")
    boolean onlyYuePay = false; // 是否只用余额支付
    @Extra("orderCode")
    String orderCode;

    private KeyboardUtil keyboardUtil;

    private View view0, view1, view2;//支付时使用的三个布局
    private List<View> viewList;//view数组

    //支付信息
    private Button btn_confirmToPayBtn;//确认按钮
    private EditText et_line1;//支付金额
    private TextView tv_payInfoTitle2;//支付类型的名称
    private TextView tv_line2;//支付金额
    private TextView tv_totalFee;//支付总金额
    private TextView tv_payType;
    private LinearLayout ll_line2;
    private View divider1;

    //选择支付方式页面
    private RelativeLayout rl_wechatQRCodePay;//微信二维码支付
    private RelativeLayout rl_wechatPay;//微信支付
    private RelativeLayout rl_yuePay;//余额支付
    private View view_masking;//余额支付上面的蒙版

    //支付页面
    private EditText et_pwd;//显示支付密码
    private String pwd = "";//支付密码
    private TextView tv_toPayFeeBtn;//支付按钮
    private ScrollView scrollView;


    private LocalBroadcastManager localBroadcastManager;//获取实例

    private static final int CONFIRM_PAY = 1;
    private boolean isConfirmPay; //记录是否可以点击确认支付


    //支付类型
    public static final String PayType_Recharge = "0";//充值
    public static final String PayType_Reflect = "4";//提现
    public static final String PayType_Freight = "1";//运费（代支付）

    private long payTotal;//最终支付金额
    private long totalMoney = Integer.MAX_VALUE;//钱包中剩余的金额

    private String dealObjectType;
    private String payTitle = "";
    private TextView tv_yueErr; //余额不足
    private TextView tv_payInfoTitle1;
    private IWXAPI msgApi;

    private Observable<String> mObservable1;
    private Observable<String> mObservable2;

    /**
     * 点击确认支付后 延时消息Handler
     */
    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case CONFIRM_PAY:
                    isConfirmPay = true; //设置可以支付
                    break;
            }
        }
    };

    @AfterViews
    void startPage() {
        localBroadcastManager = LocalBroadcastManager.getInstance(this.getApplicationContext());//获取实例
        getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);

        getWalletTotalMoney();

        initViews();
        initMoveKeyBoard();
        initDatas();

        //支付失败点击重新支付
        mObservable1 = RxBus.get().register(BroadcastChannels.Channel_Repay, String.class);
        mObservable2 = RxBus.get().register(BroadcastChannels.Channel_WeChatPaySuccessfully, String.class);
        mObservable1.subscribe(s -> {
            weiXinPay(false);
        });
        mObservable2.subscribe(s -> {
            finish();
        });


        msgApi = WXAPIFactory.createWXAPI(this, Value.WEIXIN_APP_ID);
//        msgApi = WXAPIFactory.createWXAPI(this, null);
//        msgApi.registerApp(Flag.WEIXIN_APP_ID);//将该APP注册到微信
    }

    private void initMoveKeyBoard() {
        keyboardUtil = new KeyboardUtil(this, rootView, scrollView);
        et_pwd.setOnTouchListener(new KeyboardTouchListener(keyboardUtil, KeyboardUtil.INPUTTYPE_NUM_ABC, -1));
    }

    private void initViews() {

        /**
         * 左侧关闭页面的按钮(×)
         */
        iv_finishBtn.setOnClickListener(v -> onBackPressed());

        /**
         * 左侧的返回键
         */
        iv_backBtn.setOnClickListener(v -> viewPager.setCurrentItem(1));

        /**
         * 右侧的返回键
         */
        iv_rightBackBtn.setOnClickListener(v -> {
            viewPager.setCurrentItem(1);
            pwd = "";
            et_pwd.setText(pwd);
        });

        LayoutInflater inflater = getLayoutInflater();
        view0 = inflater.inflate(R.layout.item_pay_fee_input_code_viewpager, null);
        view1 = inflater.inflate(R.layout.item_pay_fee_info_detail_viewpager, null);
        view2 = inflater.inflate(R.layout.item_pay_fee_select_pay_type_viewpager, null);

        viewList = new ArrayList<>();// 将要分页显示的View装入数组中
        viewList.add(view0);
        viewList.add(view1);
        viewList.add(view2);

        viewPager.setAdapter(pagerAdapter);
        viewPager.setNoScroll(true);
        viewPager.setCurrentItem(1);
        initPage1();
        isConfirmPay = true;
        findViews();
        initListener();
    }

    private void findViews() {
        et_pwd = (EditText) view0.findViewById(R.id.et_pwd);
        tv_toPayFeeBtn = (TextView) view0.findViewById(R.id.tv_toPayFeeBtn);
        scrollView = (ScrollView) view0.findViewById(R.id.scrollView);

        rl_wechatQRCodePay = (RelativeLayout) view2.findViewById(R.id.rl_wechatQRCodePay);
        rl_yuePay = (RelativeLayout) view2.findViewById(R.id.rl_yuePay);
        rl_wechatPay = (RelativeLayout) view2.findViewById(R.id.rl_wechatPay);
        View payTypeDivider1 = view2.findViewById(R.id.payTypeDivider1);
        tv_yueErr = (TextView) view2.findViewById(R.id.tv_yueErr);
        view_masking = view2.findViewById(R.id.view_masking);

        btn_confirmToPayBtn = (Button) view1.findViewById(R.id.btn_confirmToPayBtn);
        tv_payInfoTitle1 = (TextView) view1.findViewById(R.id.tv_payInfoTitle1);
        et_line1 = (EditText) view1.findViewById(R.id.et_line1);
        tv_payInfoTitle2 = (TextView) view1.findViewById(R.id.tv_payInfoTitle2);
        tv_line2 = (TextView) view1.findViewById(R.id.tv_line2);
        tv_totalFee = (TextView) view1.findViewById(R.id.tv_totalFee);
        tv_payType = (TextView) view1.findViewById(R.id.tv_payType);
        ll_line2 = (LinearLayout) view1.findViewById(R.id.ll_line2);
        divider1 = view1.findViewById(R.id.divider1);

        if (onlyWeChat) {//只能使用微信支付
            payTypeDivider1.setVisibility(View.GONE);
            rl_yuePay.setVisibility(View.GONE);
            setPayTypeWeChat();
        }

        if (onlyYuePay) {//只能使余额支付
            payTypeDivider1.setVisibility(View.GONE);
            rl_wechatPay.setVisibility(View.GONE);
            setPayTypeYupay();
        }
    }


    private void initDatas() {
        //初始化金额
        et_line1.setText("0");
        tv_line2.setText("0");

        payInfoType = payBean.getPayType();
        chargeLine1 = payBean.getChargeLine1();
        chargeLine2 = payBean.getChargeLine2();


        et_line1.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                chargeLine1 = changeYuan2Fen(et_line1.getText().toString().trim());
                setTotalPay();
            }
        });

        if (null != payInfoType) {
            showPayInfoDetail(payInfoType, chargeLine1, 1);
            if (chargeLine2 > 0) {
                showPayInfoDetail(payInfoType, chargeLine2, 2);
            }
        }
        setTotalPay();
        tv_title.setText(payTitle);
        rl_yuePay.setSelected(true);
    }

    /**
     * 设置总金额
     */
    private void setTotalPay() {
        payTotal = chargeLine1 + chargeLine2;
        tv_totalFee.setText(StringUtils.format2Yuan(payTotal + "") + "元");
        showYueErr();
    }


    /**
     * 展示支付的金额信息
     *
     * @param payType 支付的类型
     * @param charge  金额
     * @param line    显示要支付的行号（1或2）
     */
    private void showPayInfoDetail(String payType, long charge, int line) {

        switch (payType) {
            /**
             * 充值
             */
            case PayType_Recharge:
                if (1 == line) {
                    dealObjectType = PayType_Recharge;
                    orderCode = "androidchongzhi";
                    showLine1Charge(charge, R.string.string_payFee_payTypeRecharge);
                } else if (2 == line) {
                    showLine2Charge(charge, "");
                }
                break;

            /**
             * 提现
             */
            case PayType_Reflect:
                if (1 == line) {
                    dealObjectType = PayType_Reflect;
                    orderCode = "androidtixian";
                    btn_confirmToPayBtn.setText(getString(R.string.string_commonNext));
                    tv_toPayFeeBtn.setText(getString(R.string.string_payFee_payTypeReflect));
                    showLine1Charge(charge, R.string.string_payFee_payTypeReflect);
                } else if (2 == line) {
                    showLine2Charge(charge, "");
                }
                break;

            /**
             * 运费
             */
            case PayType_Freight:
                if (1 == line) {
                    dealObjectType = PayType_Freight;
                    showLine1Charge(charge, R.string.string_payFee_payTypeFreight);
                } else if (2 == line) {
                    showLine2Charge(charge, "");
                }
                break;
        }
    }

    /**
     * 设置支付的第一栏
     *
     * @param charge     金额
     * @param line2Title 名称
     */
    private void showLine1Charge(long charge, int line2Title) {
        payTitle = getString(line2Title);
        tv_payInfoTitle1.setText(payTitle);
        et_line1.setText(StringUtils.format2Yuan(charge + ""));
    }

    /**
     * 设置支付的第二栏
     *
     * @param charge     金额
     * @param line2Title 名称
     */
    private void showLine2Charge(long charge, String line2Title) {
        tv_payInfoTitle2.setText(line2Title);
        tv_line2.setText(StringUtils.format2Yuan(charge + ""));
        ll_line2.setVisibility(View.VISIBLE);
        divider1.setVisibility(View.VISIBLE);
    }


    private void initListener() {

        /**
         * 清除支付密码按钮的监听
         */
        view0.findViewById(R.id.iv_clearPwdBtn).setOnClickListener(v -> {
            pwd = "";
            et_pwd.setText(pwd);
        });


        /**
         * 密码长度的监听
         */
        et_pwd.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                pwd = et_pwd.getText().toString().trim();
                if (pwd.length() >= 5) {
                    tv_toPayFeeBtn.setTextColor(getResources().getColor(R.color.color_btnText));
                    tv_toPayFeeBtn.setEnabled(true);
                } else {
                    tv_toPayFeeBtn.setTextColor(getResources().getColor(R.color.color_defaultText));
                    tv_toPayFeeBtn.setEnabled(false);
                }
            }
        });


        /**
         * 付款按钮
         */
        tv_toPayFeeBtn.setOnClickListener(v -> {
            balancePay();
            animUtils.leftInAnimation(PayFeeActivity.this);
        });

        /**
         * 忘记密码
         */
        view0.findViewById(R.id.tv_forgetPwdBtn).setOnClickListener(v -> {
            RetrievePasswordActivity_.intent(PayFeeActivity.this).start();
            animUtils.leftInAnimation(PayFeeActivity.this);
        });

        /**
         * 点击付款方式
         * */
        view1.findViewById(R.id.rl_payType).setOnClickListener(v -> {
            //判断是否余额支付
            if (onlyWeChat) {
                viewPager.setCurrentItem(2);
            } else {
                //请求余额接口 获取余额 进行比较判断是否余额不足
                //loadBalancetDatas();
            }
            viewPager.setCurrentItem(2);
        });

        /**
         * 确认付款按钮
         */
        btn_confirmToPayBtn.setOnClickListener(v -> {
            if (1 == payType) {
                if (payTotal > totalMoney) {
                    App.toast(R.string.string_payFee_yuEErrorToast);
                    viewPager.setCurrentItem(2);
                    return;
                }
                //当使用余额支付时判断是否设置过支付密码
                int whetherPayPassword = sharePreferenceUtil.getWhetherPayPassword();
                if (whetherPayPassword == 0) {
                    setPwd();
                } else {
                    //余额支付
                    viewPager.setCurrentItem(0);
                }
            } else {
                initCountDown();
                weiXinPay(3 == payType);
                //判断当前是否可以支付
//                if (isConfirmPay) {
//                    isConfirmPay = false; // 点击后不可重复点击
//                    handler.sendEmptyMessageDelayed(CONFIRM_PAY, 3000);//当使用微信支付时 点击确认付款后发送延时消息
//                    weiXinPay(3 == payType);
//                }
            }
        });

        /**
         * 选择支付方式的确认按钮
         */
        view2.findViewById(R.id.tv_confirmBtn).setOnClickListener(v -> viewPager.setCurrentItem(1));

        /**
         * 选择微信二维码支付
         */
        rl_wechatQRCodePay.setOnClickListener(v -> setPayTypeWeChatQRCode());

        /**
         * 选择微信支付
         */
        rl_wechatPay.setOnClickListener(v -> setPayTypeWeChat());

        /**
         * 选择余额支付
         */
        rl_yuePay.setOnClickListener(v -> setPayTypeYupay());

        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                switch (position) {
                    case 0:
                        tv_title.setText(payTitle);
                        iv_backBtn.setVisibility(View.GONE);
                        iv_rightBackBtn.setVisibility(View.VISIBLE);
                        iv_finishBtn.setVisibility(View.GONE);
                        keyboardUtil.showKeyboard();
                        break;
                    case 1:
                        initPage1();
                        keyboardUtil.hideAllKeyBoard();
                        break;
                    case 2:
                        tv_title.setText(getString(R.string.string_payFee_title2));
                        iv_rightBackBtn.setVisibility(View.GONE);
                        iv_finishBtn.setVisibility(View.GONE);
                        iv_backBtn.setVisibility(View.VISIBLE);
                        keyboardUtil.hideAllKeyBoard();
                        break;
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    private void setPayTypeWeChatQRCode() {
        payType = 3;
        tv_payType.setText(getString(R.string.string_payFee_payType3));
        rl_wechatQRCodePay.setSelected(true);
        rl_wechatPay.setSelected(false);
        rl_yuePay.setSelected(false);
    }

    private void setPayTypeWeChat() {
        payType = 2;
        tv_payType.setText(getString(R.string.string_payFee_payType1));
        rl_wechatQRCodePay.setSelected(false);
        rl_wechatPay.setSelected(true);
        rl_yuePay.setSelected(false);
    }

    private void setPayTypeYupay() {
        payType = 1;
        tv_payType.setText(getString(R.string.string_payFee_payType2));
        rl_wechatQRCodePay.setSelected(false);
        rl_wechatPay.setSelected(false);
        rl_yuePay.setSelected(true);
    }

    /**
     * 余额支付
     */
    private void balancePay() {
        // 参数3：交易类型；1、代支付，2、还没定
        // 参数5：用户类型，派送端传2
        if (SharePreferenceUtil.getMyInfo(PayFeeActivity.this).getPayPasswordStauts().equals(Value.PayPasswordStatus_UnSet)) {
            setPwd();
        } else {
            pwd = MD5.GetMD5Code(pwd);
            MoneyBean moneyBean = new MoneyBean(pwd, Flag.DEAL_TYPE, orderCode);
            moneyBean.setMoney(payTotal + "");
            String jsonMoney = JsonUtils.createJsonString(moneyBean);
            try {
                String aesMoney = JsonUtils.aes(jsonMoney);
                callNet(PayFeeActivity.this, InterfaceNet.Net_ChangeMoney, aesMoney, new NetResultOperate() {
                    @Override
                    public void onSuccess(String content) {
                        Intent intent = new Intent();
                        intent.putExtra("paySuccess", "paySuccess");
                        setResult(Flag.ACTIVITY_PAY_FEE, intent);

                        Intent intentBroadcast = new Intent(BroadcastChannels.Channel_PayFeeSuccessFully);
                        localBroadcastManager.sendBroadcast(intentBroadcast);
                        onBackPressed();

                        App.toast("付款成功！");
                    }

                    @Override
                    public void onDataEmpty(String content) {

                    }

                    @Override
                    public void onDataEnd(String content) {

                    }

                    @Override
                    public void onErr(String errorCode, String errorMsg, Context mContext) {
                        super.onErr(errorCode, errorMsg, mContext);
                        if (errorCode.equals("1100")) {
                            pwdWrong();
                        }
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 设置支付密码
     */
    private void setPwd() {
        //创建对话框
        new AlertDialog.Builder(PayFeeActivity.this)
                .setTitle(getString(R.string.string_my_pay_pwd_set))//设置对话框标题
                .setNeutralButton("去设置", (dialogInterface, i) -> {
                    SetPasswordActivity_.intent(PayFeeActivity.this)
                            .ifModification(Value.SetPasswordType_Setting)
                            .ifSetupTradingPassword(true);
                    animUtils.leftInAnimation(PayFeeActivity.this);
                })
                .setNegativeButton("取消", (dialog, which) -> dialog.dismiss())//设置对话框[否定]按钮
                .show();
    }

    /**
     * 密码错误
     */
    private void pwdWrong() {
        new AlertDialog.Builder(PayFeeActivity.this)
                .setTitle(getString(R.string.string_my_pay_pwd_wrong))//设置对话框标题
                .setNeutralButton(getString(R.string.string_my_retrieve_password_title), (dialogInterface, i) -> {
                    RetrievePasswordActivity_.intent(PayFeeActivity.this).start();
                    animUtils.leftInAnimation(PayFeeActivity.this);
                })
                .setNegativeButton("取消", (dialog, which) -> dialog.dismiss())//设置对话框[否定]按钮
                .show();
    }

    /**
     * 微信支付
     */
    private void weiXinPay(boolean isQRCodePay) {

        if (payTotal <= 0) {
            App.toast("支付金额需要大于0！");
            return;
        }

        String userId = (new BaseBean()).getUserId();
        String loginName = (new BaseBean()).getLoginName();
        /**
         * dealObject:支付类型
         * objectCode:订单号
         */
        String attachStr = "'dealObject':'" + dealObjectType + "',"
                + "'userId':'" + userId + "',"
                + "'loginName':'" + loginName + "',"
                + "'objectCode':'" + orderCode + "','userType':'2'";
        //TODO 测试使用支付1分钱
//        MoneyBean weiXinEntity = new MoneyBean(attachStr, payTitle, "123.12.12.123", "1");

        //TODO 正式时调用
        MoneyBean weiXinEntity = new MoneyBean(attachStr, payTitle, "123.12.12.123", payTotal + "");
        if (isQRCodePay) {
            weiXinEntity.setTrade_type(MoneyBean.TradeType_QRCode);
        } else {
            weiXinEntity.setTrade_type(MoneyBean.TradeType_APP);
        }

        String jsonWeiXin = JsonUtils.createJsonString(weiXinEntity);
        try {
            String aesWeiXin = JsonUtils.aes(jsonWeiXin);
            callNet(PayFeeActivity.this, InterfaceNet.Net_GetWeChatPayParam, aesWeiXin, new NetResultOperate() {
                @Override
                public void onSuccess(String content) {
                    LogUtils.log("微信支付receive---" + content);
                    if (!StringUtils.isEmpty(content)) {
                        try {

                            JSONObject weixinJson = new JSONObject(content);
                            if (null != weixinJson && !weixinJson.has("retcode")) {
                                if (isQRCodePay) {
                                    String qrCode = weixinJson.getString("codeurl");
                                    showPayQRCOde(qrCode);
                                } else {
                                    PayReq payReq = new PayReq();
                                    payReq.appId = weixinJson.getString("appid");
                                    payReq.partnerId = weixinJson.getString("partnerid");
                                    payReq.prepayId = weixinJson.getString("prepayid");
                                    payReq.nonceStr = weixinJson.getString("noncestr");
                                    payReq.timeStamp = weixinJson.getString("timestamp");
                                    payReq.packageValue = weixinJson.getString("package");
                                    payReq.sign = weixinJson.getString("sign");
                                    payReq.extData = "app data"; // optional
                                    // 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
                                    boolean b = msgApi.sendReq(payReq);
                                    LogUtils.log("微信支付payReq---" + b);
                                }
                            } else {
                                LogUtils.log("微信支付retmsg---" + weixinJson.getString("retmsg"));
                                App.toast("返回错误"
                                        + weixinJson.getString("retmsg"));
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }

                @Override
                public void onDataEmpty(String content) {

                }

                @Override
                public void onDataEnd(String content) {

                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            LogUtils.log("微信支付retmsg---abc");
        }
    }

    /**
     * 显示支付的二维码
     *
     * @param qrCode
     */
    private void showPayQRCOde(String qrCode) {
        Observable
                .create(new Observable.OnSubscribe<Bitmap>() {
                    @Override
                    public void call(Subscriber<? super Bitmap> subscriber) {
                        Bitmap logoBitmap = BitmapFactory.decodeResource(PayFeeActivity.this.getResources(), R.mipmap.ic_launcher);
                        Bitmap bitmap = QRCodeEncoder.syncEncodeQRCode(qrCode,
                                BGAQRCodeUtil.dp2px(PayFeeActivity.this, 200),
                                Color.BLACK, Color.TRANSPARENT, logoBitmap);
                        if (null == bitmap) {
                            subscriber.onError(new Throwable("生成二维码失败！"));
                            LogUtils.log("生成二维码失败~~~");
                        } else {
                            subscriber.onNext(bitmap);
                        }
                        subscriber.onCompleted();
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<Bitmap>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                        App.toast("生成二维码失败！");
                    }

                    @Override
                    public void onNext(Bitmap bitmap) {

                        LayoutInflater inflater = getLayoutInflater();
                        View view = inflater.inflate(R.layout.dialog_show_wechat_qrcode, null);
                        ImageView iv_qrcode = (ImageView) view.findViewById(R.id.iv_qrcode);
                        iv_qrcode.setImageBitmap(bitmap);
                        new android.app.AlertDialog.Builder(PayFeeActivity.this)
                                .setView(view)
                                .show();
                    }
                });
    }

    private void initPage1() {
        tv_title.setText(payTitle);
        iv_backBtn.setVisibility(View.GONE);
        iv_rightBackBtn.setVisibility(View.GONE);
        iv_finishBtn.setVisibility(View.VISIBLE);
    }

    private PagerAdapter pagerAdapter = new PagerAdapter() {

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == arg1;
        }

        @Override
        public int getCount() {
            return viewList.size();
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView(viewList.get(position));
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            container.addView(viewList.get(position));
            return viewList.get(position);
        }
    };

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        animUtils.popOutAnimation(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        RxBus.get().unregister(BroadcastChannels.Channel_Repay, mObservable1);
        RxBus.get().unregister(BroadcastChannels.Channel_WeChatPaySuccessfully, mObservable2);
    }

    /**
     * 从网络获取余额数据
     */
    private void getWalletTotalMoney() {
        WalletEntity entity = new WalletEntity(this);
        String walletJson = JsonUtils.createJsonString(entity);
        try {
            String aes = JsonUtils.aes(walletJson);
            callNet(this, InterfaceNet.Net_GetWalletTotalMoney, aes, new NetResultOperate() {
                @Override
                public void onSuccess(String content) {
                    if (!StringUtils.isEmpty(content)) {
                        WalletEntity walletEntity = (WalletEntity) JsonUtils.parseJsonString(content, WalletEntity.class);
                        totalMoney = Long.valueOf(walletEntity.getTotalMoney());
                        showYueErr();
                    }
                }

                @Override
                public void onDataEmpty(String content) {
                }

                @Override
                public void onDataEnd(String content) {
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 将元转化成分
     *
     * @param yuan 元
     * @return
     */
    private long changeYuan2Fen(String yuan) {
        long result = 0;
        try {
            result = Long.valueOf(yuan) * 100;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 显示余额不足
     */
    @UiThread
    void showYueErr() {
        boolean isShow = payTotal > totalMoney;
        rl_yuePay.setEnabled(!isShow);
        if (isShow) {
            tv_yueErr.setVisibility(View.VISIBLE);
            view_masking.setVisibility(View.VISIBLE);
        } else {
            tv_yueErr.setVisibility(View.GONE);
            view_masking.setVisibility(View.GONE);
        }
    }

    /* 初始化倒计时 */
    private void initCountDown() {
        TimeCountDownUtil timeCountDown = new TimeCountDownUtil(this, 9 * 1000, 1000,
                btn_confirmToPayBtn, R.string.string_payFee_confirmToPayBtn);
        timeCountDown.start();
    }
}